# coding = UTF-8
import optparse
import socket
import threading

screenLock=threading.Semaphore(value=1)
def connScan(tgtHost, tgtPort):
    try:
        connSkt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        connSkt.connect((tgtHost, tgtPort))
        connSkt.send("ViolentPython\r\n")
        results=connSkt.recv(100)
        screenLock.acquire()
        print('[+]%d/tcp open' % tgtPort)
        print('[+]'+str(results))
    except:
        screenLock.acquire()
        print ('[+]%d/tcp closed' % tgtPort)
    finally:
        screenLock.release()
        connSkt.close()

def portScan(tgtHost, tgtPort):
    try:
        tgtip = socket.gethostbyname(tgtHost)
    except:
        print ("[-] Cannot resolve '%s': Unknown host" % tgtHost)
        return
    try:
        tgtName = socket.gethostbyaddr(tgtip)
        print ('\n[+]Scan Results for:' + tgtName[0])
    except:
        print('\n[+] Scan Results for:' + tgtip)

    socket.setdefaulttimeout(1)
    for tgtPort in tgtPort:
        print ('Scanning port ' + str(tgtPort))
        #connScan(tgtHost, int(tgtPort))
        t=threading.Thread(target=connScan,args=(tgtHost,int(tgtPort)))
        t.start()

#portScan('www.baidu.com', [80, 443, 3389, 1433, 23, 445, 1433, 3306])

def main():
    parser = optparse.OptionParser('usage %prog -H <targethost> -p <target port>')
    parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
    parser.add_option('-p', dest='tgtPort', type='int', help='specify target port')
    (options, args) = parser.parse_args()
    tgtHost = options.tgtHost
    tgtPort = options.tgtPort
    args.append(tgtPort)
    if (tgtHost is None) or (tgtPort is None):
        print ('[-] You must specify a target host and port[s]!')
        print (parser.usage)
        exit(0)
    portScan(tgtHost,args)
if __name__=='__main__':
    main()
